<template>
  <section class="comments">
    <h2 class="head">评论 <span class="count">{{ items.length }}</span></h2>

    <form class="editor" @submit.prevent="submit">
      <div class="avatar" aria-hidden="true">{{ initials(user?.username || '你') }}</div>
      <textarea v-model="text" :placeholder="user ? '发一条友善的评论吧' : '登录后发表评论'" rows="3" :disabled="!user"></textarea>
      <div class="actions">
        <button type="submit" :disabled="!text.trim() || !user">{{ user ? '发布' : '登录后发布' }}</button>
        <button v-if="!user" type="button" class="login" @click="goLogin">去登录</button>
      </div>
    </form>

    <ul class="list">
      <li v-for="c in sorted" :key="c.id" class="item">
        <div class="avatar" :title="c.user">{{ initials(c.user) }}</div>
        <div class="body">
          <div class="line">
            <span class="user">{{ c.user }}</span>
            <span class="time">{{ fmt(c.time) }}</span>
          </div>
          <p class="content">{{ c.content }}</p>
          <div class="ops">
            <button class="like" @click="like(c)">👍 {{ c.likes }}</button>
            <button class="reply" @click="toggleReply(c)">回复</button>
          </div>
          
          <!-- 回复表单 -->
          <div v-if="replyingTo === c.id" class="reply-editor">
            <form @submit.prevent="submitReply(c)">
              <textarea v-model="replyText" :placeholder="`回复 @${c.user}`" rows="2" :disabled="!user"></textarea>
              <div class="reply-actions">
                <button type="button" class="cancel" @click="cancelReply">取消</button>
                <button type="submit" :disabled="!replyText.trim() || !user">回复</button>
              </div>
            </form>
          </div>
          
          <!-- 回复列表 -->
          <div v-if="c.replies && c.replies.length > 0" class="replies">
            <ul class="reply-list">
              <li v-for="reply in c.replies" :key="reply.id" class="reply-item">
                <span class="reply-user">{{ reply.user }}</span>
                <span class="reply-to">回复 @{{ c.user }}</span>：
                <span class="reply-content">{{ reply.content }}</span>
                <span class="reply-time">{{ fmt(reply.time) }}</span>
                <button class="reply-like" @click="likeReply(c, reply)">👍 {{ reply.likes }}</button>
              </li>
            </ul>
          </div>
        </div>
      </li>
    </ul>
  </section>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import comments from '@/data/comments'
import { getCurrentUser } from '@/utils/auth'

const props = defineProps({ videoId: { type: [String, Number], required: true } })
const router = useRouter()
const text = ref('')
const replyText = ref('')
const replyingTo = ref(null)

// 将 user 由 computed 改为 ref，并监听事件以实时更新
const user = ref(getCurrentUser())
const updateUser = () => { user.value = getCurrentUser() }
onMounted(() => {
  window.addEventListener('auth-changed', updateUser)
  window.addEventListener('storage', updateUser)
})
onUnmounted(() => {
  window.removeEventListener('auth-changed', updateUser)
  window.removeEventListener('storage', updateUser)
})

// 使用本地响应式列表，提交后立即更新
const items = ref([])
function initList() {
  // 获取评论并确保每个评论都有replies数组
  items.value = comments.filter(c => String(c.videoId) === String(props.videoId)).map(c => ({
    ...c,
    replies: c.replies || []
  }))
}
initList()
watch(() => props.videoId, () => initList())

const sorted = computed(() => [...items.value].sort((a, b) => new Date(b.time) - new Date(a.time)))

function submit() {
  const content = text.value.trim()
  if (!content || !user.value) return
  const id = (comments.at(-1)?.id || 0) + 1
  const entry = { 
    id, 
    videoId: Number(props.videoId), 
    user: user.value.username, 
    content, 
    time: new Date().toISOString(), 
    likes: 0,
    replies: []
  }
  comments.push(entry) // 更新全局数据
  items.value.push(entry) // 立即更新本地响应式列表
  text.value = ''
}

function toggleReply(comment) {
  if (!user.value) {
    goLogin()
    return
  }
  replyingTo.value = replyingTo.value === comment.id ? null : comment.id
  if (replyingTo.value === comment.id) {
    replyText.value = ''
  }
}

function cancelReply() {
  replyingTo.value = null
  replyText.value = ''
}

function submitReply(comment) {
  const content = replyText.value.trim()
  if (!content || !user.value) return
  
  const replyId = Date.now() // 使用时间戳作为回复ID
  const reply = {
    id: replyId,
    user: user.value.username,
    content,
    time: new Date().toISOString(),
    likes: 0
  }
  
  // 确保replies数组存在
  if (!comment.replies) {
    comment.replies = []
  }
  
  comment.replies.push(reply)
  replyingTo.value = null
  replyText.value = ''
}

function like(comment) {
  comment.likes++
}

function likeReply(comment, reply) {
  reply.likes++
}

function fmt(t) { 
  const d = new Date(t); 
  const now = new Date();
  const diff = now - d;
  
  // 如果是今天的评论，显示具体时间
  if (diff < 86400000 && d.toDateString() === now.toDateString()) {
    return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 如果是今年的评论，显示月日和时间
  if (d.getFullYear() === now.getFullYear()) {
    return d.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }) + ' ' + 
           d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 其他情况显示完整日期
  return d.toLocaleString('zh-CN');
}

function initials(name) { 
  return (name || '?').slice(0, 1).toUpperCase() 
}

function goLogin() { 
  router.push('/login') 
}
</script>

<style scoped>
.comments { margin-top: 20px; }
.head { margin: 16px 4px 8px; font-size: 18px; font-weight: 700; }
.count { color: var(--muted); font-weight: 400; font-size: 14px; margin-left: 6px; }
.editor { display: grid; grid-template-columns: 40px 1fr; gap: 10px; align-items: start; margin: 8px 0 16px; }
.editor .avatar { width: 40px; height: 40px; border-radius: 50%; background: #e6f7ff; color: #0077b8; display: inline-flex; align-items: center; justify-content: center; font-weight: 700; }
.editor textarea { width: 100%; padding: 10px 12px; border-radius: var(--radius); border: 1px solid var(--border); resize: vertical; background: #fff; color: #374151; outline: none; transition: box-shadow 0.2s ease, border-color 0.2s ease; }
.editor textarea:disabled { background: #f9fafb; }
.editor textarea:focus { border-color: #b7dff1; box-shadow: 0 0 0 3px rgba(0,161,214,0.18); }
.editor .actions { grid-column: 2; display: flex; gap: 8px; justify-content: flex-end; margin-top: 8px; }
.editor button { padding: 8px 14px; border-radius: 999px; background: linear-gradient(90deg, #00a1d6, #06b6d4); color: #fff; border: none; cursor: pointer; }
.editor .login { padding: 8px 14px; border-radius: 999px; background: #fff; color: #374151; border: 1px solid var(--border); cursor: pointer; }
.editor button:disabled { opacity: 0.6; cursor: not-allowed; }
.list { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; }
.item { display: grid; grid-template-columns: 40px 1fr; gap: 10px; }
.item .avatar { width: 40px; height: 40px; border-radius: 50%; background: #eef2f7; color: #6b7280; display: inline-flex; align-items: center; justify-content: center; font-weight: 700; }
.body { background: #fff; border: 1px solid var(--border); border-radius: var(--radius); padding: 10px 12px; box-shadow: var(--shadow-sm); }
.line { display: flex; gap: 8px; align-items: baseline; }
.user { font-weight: 700; }
.time { color: var(--muted); font-size: 12px; }
.content { margin: 6px 0 8px; white-space: pre-wrap; word-break: break-word; }
.ops { display: flex; gap: 16px; }
.like, .reply { border: 1px solid var(--border); background: #fff; color: #374151; border-radius: 999px; padding: 4px 10px; cursor: pointer; transition: border-color 0.2s ease, transform 0.08s ease; font-size: 13px; }
.like:hover, .reply:hover { border-color: #cfd2d6; }
.like:active, .reply:active { transform: scale(0.98); }

/* 回复编辑器样式 */
.reply-editor {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}
.reply-editor textarea {
  width: 100%;
  padding: 8px 10px;
  border-radius: var(--radius);
  border: 1px solid var(--border);
  resize: vertical;
  background: #fff;
  color: #374151;
  outline: none;
  font-size: 14px;
  transition: box-shadow 0.2s ease, border-color 0.2s ease;
}
.reply-editor textarea:focus {
  border-color: #b7dff1;
  box-shadow: 0 0 0 3px rgba(0,161,214,0.18);
}
.reply-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 8px;
}
.reply-actions .cancel {
  padding: 6px 12px;
  border-radius: 999px;
  background: #fff;
  color: #374151;
  border: 1px solid var(--border);
  cursor: pointer;
  font-size: 13px;
}
.reply-actions button[type="submit"] {
  padding: 6px 12px;
  border-radius: 999px;
  background: linear-gradient(90deg, #00a1d6, #06b6d4);
  color: #fff;
  border: none;
  cursor: pointer;
  font-size: 13px;
}
.reply-actions button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 回复列表样式 */
.replies {
  margin-top: 12px;
  padding-left: 20px;
  border-left: 2px solid #f0f0f0;
}
.reply-list {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.reply-item {
  padding: 8px 10px;
  background: #f9fafb;
  border-radius: var(--radius);
  font-size: 14px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}
.reply-user {
  font-weight: 700;
  color: #374151;
}
.reply-to {
  color: #6b7280;
  font-size: 12px;
}
.reply-content {
  color: #374151;
  flex: 1;
}
.reply-time {
  color: var(--muted);
  font-size: 11px;
  order: 1;
}
.reply-like {
  border: 1px solid var(--border);
  background: #fff;
  color: #374151;
  border-radius: 999px;
  padding: 2px 6px;
  cursor: pointer;
  font-size: 12px;
  transition: border-color 0.2s ease;
}
.reply-like:hover {
  border-color: #cfd2d6;
}
</style>